package com.shanghaionstar.login.register;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.joinme.RegisterResponseEntity;
import com.onstar.cn.mag.joinme.RegisterToVisitorResponse;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.login.LoginActivity;
import com.shanghaionstar.login.register.iview.IJoinMeView;
import com.shanghaionstar.login.register.presenter.JoinMePresenter;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.weight.CommonInputLayout;
import com.shanghaionstar.weight.CommonProgressButton;
import com.shanghaionstar.weight.TopLayout;

import java.util.Locale;

/**
 * Created by 7828wc on 16/7/1.
 * 输入VIN/证件号进行安吉星注册
 */
@ContentView(R.layout.joinme_vin_register)
public class JoinMeVinActivity extends SwipeActivity implements IJoinMeView {
    @FindViewById
    private CommonInputLayout et_vin_card, et_captcha;
    @FindViewById
    private Button btn_update_image;
    @FindViewById
    private RelativeLayout captcha_layout, info_rl;
    @FindViewById
    private TextView apply_xieyi, register_visitor, validate_name_tv, xieyi_car;
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private CommonProgressButton btn_submit;
    @FindViewById
    private EditText first_name_et, last_name_et;

    private JoinMePresenter presenter;

    private boolean isUpgradeSubscriber = false;

    private boolean isInfo3Subscriber = false;
    private boolean hasCheckInfo3 = false;

    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        apply_xieyi.setText(Html.fromHtml("<font color='#9c9da0' size='24px'>"
//                + getResources().getString(R.string.read_check) + "</font><font color='#000000' size='24px'>"
//                + getResources().getString(R.string.xieyi2) + "</font><font color='#9c9da0' size='24px'>"
//                + getResources().getString(R.string.xieyi_plus) + "</font>"
//        +"<font color='#000000' size='24px'>" + getResources().getString(R.string.xieyi_car)+"</font>"));
        presenter = new JoinMePresenter(getScheduler());

        String xieyi_text = getResources().getString(R.string.xieyi_text);
        String xieyi_onstar = getResources().getString(R.string.xieyi_onstar);
//        String xieyi_car = getResources().getString(R.string.xieyi_car);
        int start_index_onstar = xieyi_text.indexOf(xieyi_onstar);
        int end_index_onstar = start_index_onstar + xieyi_onstar.length();
//        int start_index_car = xieyi_text.indexOf(xieyi_car);
//        int end_index_car = start_index_car + xieyi_car.length();

        SpannableStringBuilder builder = new SpannableStringBuilder(xieyi_text);
        builder.setSpan(new ClickableSpan() {
                            @Override
                            public void onClick(View widget) {
                                presenter.sendReport(FunctionNameFindId.Register_Onstarserviceprotocol);
                                startActivity(new Intent(JoinMeVinActivity.this, com.shanghaionstar.user.TermsConditionsActivity.class));
                            }

                            @Override
                            public void updateDrawState(TextPaint ds) {
                                super.updateDrawState(ds);
                                ds.setUnderlineText(false);
                                ds.setColor(getResources().getColor(R.color.blackColor));
                            }
                        }, start_index_onstar, end_index_onstar,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.setSpan(new ClickableSpan() {
//                            @Override
//                            public void onClick(View widget) {
//                                Toast.makeText(JoinMeVinActivity.this, "click car xieyi", Toast.LENGTH_SHORT).show();
//                            }
//
//                            @Override
//                            public void updateDrawState(TextPaint ds) {
//                                super.updateDrawState(ds);
//                                ds.setUnderlineText(false);
//                                ds.setColor(getResources().getColor(R.color.blackColor));
//                            }
//                        }, start_index_car, end_index_car,
//                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        apply_xieyi.setMovementMethod(LinkMovementMethod.getInstance());
        apply_xieyi.setHighlightColor(getResources().getColor(android.R.color.transparent));
        apply_xieyi.setText(builder);

        presenter.setView(this);

        isUpgradeSubscriber = getIntent().getBooleanExtra("isUpgradeToSub", false);

        btn_submit.setButtonEnabled(false);
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.hideKeyBoard(onActivity(), et_vin_card.getEditValue());
                if (info_rl.getVisibility() == View.VISIBLE && TextUtils.isEmpty(first_name_et.getText()) ||
                        (info_rl.getVisibility() == View.VISIBLE &&
                                TextUtils.isEmpty(last_name_et.getText()))) {
                    validate_name_tv.setVisibility(View.VISIBLE);
                    return;
                } else {
                    validate_name_tv.setVisibility(View.GONE);
                    presenter.registerOwnerByVinOrGovId(et_vin_card.getText(), et_captcha.getText(), isUpgradeSubscriber, "", "", "", "", first_name_et.getText().toString(), last_name_et.getText().toString());
                    presenter.sendReport(FunctionNameFindId.Register_Registration);
                }

//                Intent intent = new Intent(JoinMeVinActivity.this, FinishVinRegisterActivity.class);
//                intent.putExtra("vinNumber", "123");
//                intent.putExtra("isVin", CommonUtil.isVin(et_vin_card.getText()));
//                intent.putExtra("userEmail", "zhang@163.com");
//                intent.putExtra("userNewEmail", "");
//                intent.putExtra("userPhone", "");
//                startActivityForResult(intent, 2);

            }
        });

        et_vin_card.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //用户点击第二个输入框，第一个失去焦点
                if (!hasFocus && !hasCheckInfo3 && !TextUtils.isEmpty(et_vin_card.getText())) {
                    hasCheckInfo3 = true;
//                    et_vin_card.setText("LSGGH55L0J0060212");
                    String vinOrGov = et_vin_card.getText();
                    presenter.getVehicleUnit(vinOrGov);
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //升级为车主
        if (isUpgradeSubscriber) {
            top_layout.setTopTitle(getResources().getString(R.string.upgradetoowner));
            //  升级为车主功能 去掉register_visitor_layout
            register_visitor.setVisibility(View.GONE);
        }

        presenter.getCaptchaImage();
    }


    @OnClick({R.id.btn_update_image, R.id.register_visitor})
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.btn_submit:
////                if (!select_checkbox.isChecked()) {
////                    AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.consent_terms_conditions);
////                    return;
////                }
//                presenter.registerOwnerByVinOrGovId(et_vin_card.getText(), et_captcha.getText(), isUpgradeSubscriber,"","","","");
//                break;
            case R.id.btn_update_image:
                presenter.getCaptchaImage();
                break;
            case R.id.register_visitor:
                presenter.sendReport(FunctionNameFindId.Register_NonOwner);
                Intent intent = new Intent(this, RegisterVisitorActivity.class);
                startActivityForResult(intent, 2);
                break;

/*            case R.id.apply_xieyi:
              //  CommonUtil.hideKeyBoard(this, et_vin_card);
                Intent intents = new Intent(this, TermsConditionsActivity.class);
                startActivity(intents);
                break;*/
//            case R.id.apply_xieyi_car:
//                presenter.sendReport(FunctionNameFindId.Register_Onstarserviceprotocol);
//                startActivity(new Intent(this, com.shanghaionstar.user.TermsConditionsActivity.class));
//                break;
            default:
                break;
        }
    }

    @Override
    public void showCaptchaImage(byte[] image) {
        showCaptchaView(true);
        et_captcha.showLoading(false);
        et_captcha.setCheckHintText(R.string.input_img_captcha_value);
        if (image != null) {
            et_captcha.setRightIcon(image);
        }
        btn_update_image.setVisibility(View.VISIBLE);
    }

    @Override
    public void showCaptchaView(boolean isShow) {
        captcha_layout.setVisibility(isShow ? View.VISIBLE : View.GONE);
        if (isShow) {
            btn_update_image.setVisibility(View.GONE);
            et_captcha.showLoading(true);
        }
    }

    @Override
    public void verifyInputResult(boolean result) {
        et_vin_card.setCheckHintText(result ? "" : getString(R.string.input_user_info_not_null));
    }

    @Override
    public void verifyCaptchaResult(String result) {
        et_captcha.setCheckHintText(result);
    }

    @Override
    public void setLoading(boolean isLoading) {
        btn_submit.showLoading(isLoading);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
        if (!btn_submit.isButtonEnable()) {
//            et_vin_card.setRightIcon(R.drawable.search);
            et_vin_card.setRightBtnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String vinOrGov = et_vin_card.getText();
                    presenter.getVehicleUnit(vinOrGov);
                    et_vin_card.setRightBtnVisible(false);
                }
            });
        }
    }

    @Override
    public void onResponseUpgradeSuccess(RegisterToVisitorResponse registerToVisitorResponse) {
        log.d(registerToVisitorResponse + "");
        AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), registerToVisitorResponse.getBbwcMessage(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                AuthorUtil authorUtil = new AuthorUtil();
                authorUtil.loginOut(onActivity());

                Intent intent = new Intent(onActivity(), LoginActivity.class);
                startActivity(intent);

                setResult(RESULT_OK);
                finish();
            }
        });

    }

    @Override
    public void showInfoThreeView(boolean isShow) {
        btn_submit.setButtonEnabled(true);
        isInfo3Subscriber = isShow;
        info_rl.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void showInfoLoading(boolean isLoading) {
        et_vin_card.showLoading(isLoading);
    }

    @Override
    public void onReponseSuccess(RegisterResponseEntity object) {
        log.d(object + "");
        Intent intent = new Intent(this, FinishVinRegisterActivity.class);
        intent.putExtra("vinNumber", et_vin_card.getText().toUpperCase(Locale.CHINA));
        intent.putExtra("isVin", CommonUtil.isVin(et_vin_card.getText()));
        intent.putExtra("userEmail", !CommonUtil.isNull(object.getIsEmailUnique()) && object.getIsEmailUnique().equalsIgnoreCase("true") ? object.getEmailAddress() : "");
        intent.putExtra("userNewEmail", !CommonUtil.isNull(object.getIsEmailUnique()) && object.getIsEmailUnique().equalsIgnoreCase("true") ? object.getEmailAddress() : "");
        intent.putExtra("userPhone", !CommonUtil.isNull(object.getIsMobileUnique()) && object.getIsMobileUnique().equalsIgnoreCase("true") ? object.getMobilePhoneNumber() : "");
        intent.putExtra("isInfo3", isInfo3Subscriber);
        if (isInfo3Subscriber) {
            intent.putExtra("firstName", first_name_et.getText().toString());
            intent.putExtra("lastName", last_name_et.getText().toString());
        }
        startActivityForResult(intent, 2);
    }

    @Override
    public void verifyResult(View view, int errorResId) {

    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2 && resultCode == RESULT_OK) {
            finish();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
